package controllers;

import models.Board;
import play.mvc.Controller;

import java.util.HashMap;

/**
 * Application.java is the main controller
 */
public class Application extends Controller {

    /**
     * This action is the root action in the application.
	 * It renders the initial view.
     */
    public static void index()
    {
        render();
    }

	/**
	 * This action is called through AJAX when user does a move in the game.
	 * This action returns json data to the view so it's possible to render the computers move
	 * or to display the winner.
	 * @param playerMove	The move player does, from AJAX post.
	 */
	public static void doMove(int playerMove)
    {
        Board myBoard = Board.getFromSession();
		HashMap<String, Object> ret = new HashMap<String, Object>();
		if (myBoard.getWinner() == '-' && myBoard.getMark(playerMove) == '-') {
			myBoard.setBoxes(playerMove, 'x');
			if (myBoard.getWinner() == '-') {
				int computerMove = myBoard.getComputerMove();
				myBoard.setBoxes(computerMove, 'o');
				if (myBoard.getWinner() == '-') {
					ret.put("computerMove", computerMove);
				}
				else {
					ret.put("computerMove", computerMove);
					ret.put("winner", myBoard.getWinner());
				}
			}
			else {
				char winner = myBoard.getWinner();
				if (winner == 'p') {
					ret.put("winner", "draw");
				}
				else {
					ret.put("winner", winner);
				}
			}
		}
		renderJSON(ret);
    }

	/**
	 * This action is called through AJAX to start a new game.
	 */
    public static void startNewGame()
    {
        Board myBoard = Board.getFromSession();
        myBoard.initBoard( );
    }

	/**
	 * This action is called through AJAX to render the game's status on browser refresh
	 * if the user accidentally refreshes the browser in the middle of a game.
	 */
    public static void showStatus()
    {
        Board myBoard = Board.getFromSession();
        renderJSON( myBoard.getBoxes() );
    }
}